package backed.controller;

import backed.entity.EcoBehavior;
import backed.service.BehaviorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "环保行为", description = "环保行为记录和统计相关接口")
@RestController
@CrossOrigin
@RequestMapping("/api/eco-behavior")
public class BehaviorController {
    @Autowired
    private BehaviorService behaviorService;

    @Operation(summary = "记录环保行为", description = "记录用户的环保行为，自动计算减碳量和碳积分")
    @io.swagger.v3.oas.annotations.Parameters({
        @Parameter(name = "userId", description = "用户ID", required = true, example = "1"),
        @Parameter(name = "behaviorType", description = "行为类型：walking/cycling/public_transport/recycling/energy_saving", required = true, example = "walking"),
        @Parameter(name = "value", description = "行为数值（如：步行公里数、骑行公里数等）", required = true, example = "5")
    })
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "记录成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误")
    })
    @PostMapping("/record")
    public ResponseEntity<?> record(@RequestParam long userId,
                                    @RequestParam String behaviorType,
                                    @RequestParam long value) {
        Map<String,Object> result = new HashMap<>();
        EcoBehavior ecoBehavior = behaviorService.record(userId,behaviorType,value);
        result.put("success",true);
        Map<String,Object> data = new HashMap<>();
        data.put("carbonReduction",ecoBehavior.getCarbonReduction());
        data.put("carbonPoints",ecoBehavior.getCarbonPoints());
        result.put("data",data);

        return ResponseEntity.ok(result);
    }



    @Operation(summary = "个人环保数据统计", description = "获取用户的环保行为统计数据，包括总减碳量、总积分和各行为类型统计")
    @GetMapping("/statistics")
    public ResponseEntity<?> getStatistics(
            @Parameter(description = "用户ID", required = true) 
            @RequestParam long user_id) {
        // 调用服务层获取统计数据
        Map<String, Object> statistics = behaviorService.getStatistics(user_id);
        
        // 构建符合API文档要求的响应格式
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", statistics);
        
        return ResponseEntity.ok(result);
    }


    @Operation(summary = "环保贡献趋势图数据", description = "获取指定日期范围内的环保行为趋势数据")
    @GetMapping("/trends")
    public ResponseEntity<?> getTrends(
            @Parameter(description = "用户ID", required = true) @RequestParam long user_id,
            @Parameter(description = "开始日期", example = "2025-01-01") @RequestParam LocalDate startDate,
            @Parameter(description = "结束日期", example = "2025-01-31") @RequestParam LocalDate endDate) {
        // 调用服务层获取趋势数据
        List<Map<String, Object>> trendData = behaviorService.trend(user_id, startDate, endDate);
        
        // 构建符合API文档要求的响应格式
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", trendData);
        
        return ResponseEntity.ok(result);
    }
    
    @Operation(summary = "碳积分排行榜", description = "获取不同时间维度的碳积分排行榜")
    @GetMapping("/ranking")
    public ResponseEntity<?> getRanking(
            @Parameter(description = "排行榜类型：daily/weekly/monthly/all", required = true) 
            @RequestParam String type,
            @Parameter(description = "返回数量限制", required = true) 
            @RequestParam int limit) {
        // 验证类型参数
        if (!List.of("daily", "weekly", "monthly", "all").contains(type)) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "无效的排行榜类型，请使用：daily/weekly/monthly/all");
            return ResponseEntity.badRequest().body(errorResult);
        }
        
        // 调用服务层获取排行榜数据
        List<Map<String, Object>> rankingData = behaviorService.getRanking(type, limit);
        
        // 为每条数据添加排名
        for (int i = 0; i < rankingData.size(); i++) {
            rankingData.get(i).put("rank", i + 1);
        }
        
        // 构建符合API文档要求的响应格式
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", rankingData);
        
        return ResponseEntity.ok(result);
    }
}
